package com.suishoupai.xmb.service;

import com.suishoupai.xmb.dao.CategoryMapper;
import com.suishoupai.xmb.dao.CutCategoryMapper;
import com.suishoupai.xmb.dao.CutUserSaleMapper;
import com.suishoupai.xmb.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by caojian on 2017/3/30.
 */
@Service
public class CategoryService {
    @Autowired
    private CutCategoryMapper cutCategoryMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CutUserSaleMapper cutUserSaleMapper;

    @Value("${sale.category_max_number}")
    private int CATEGORY_MAX_NUMBER;

    public List<Category> getListBySaleId(long saleId) {
        return cutCategoryMapper.selectBySaleId(saleId);
    }

    /**
     * 添加分类
     *
     * @param category
     */
    @Transactional
    public void add(Category category) {
        category.setCreateTime(System.currentTimeMillis());
        if (categoryMapper.insertSelective(category) == 0) {
            throw new RuntimeException("插入失败！");
        }
        if (cutUserSaleMapper.addCategoryNumber(category.getSaleId(), CATEGORY_MAX_NUMBER) == 0) {
            throw new RuntimeException("插入失败！");
        }
    }

    /**
     * 更新
     *
     * @param category
     */
    public void update(Category category) {
        if (cutCategoryMapper.updateByPrimaryKeySelective(category) == 0) {
            throw new RuntimeException("更新失败！");
        }
    }

    /**
     * 删除
     *
     * @param categoryId
     * @param saleId
     */
    public void delete(long categoryId, long saleId) {
        if (cutCategoryMapper.deleteByPrimaryKey(categoryId) == 0) {
            throw new RuntimeException("删除失败！");
        }
        if (cutUserSaleMapper.reduceCategoryNumber(saleId) == 0) {
            throw new RuntimeException("删除失败！");
        }
    }
}
